package com.bw.module_attendance.view

import android.annotation.SuppressLint
import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.path.RouterPath
import com.bw.lib_common.view.BaseMvvmActivity
import com.bw.module_attendance.R
import com.bw.module_attendance.databinding.ActivityClockInBinding
import com.bw.module_attendance.entity.AttendanceEntity
import com.bw.module_attendance.viewmodel.AttendanceViewModel
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

/**
 * 工单-智慧园区-考勤管理
 */
@Route(path = RouterPath.PATH_CLOCK_IN_ACTIVITY)
class ClockInActivity : BaseMvvmActivity<ActivityClockInBinding>() {
    private val vm by lazy { ViewModelProvider(this)[AttendanceViewModel::class.java] }
    private val timer:Timer = Timer()
    var lat = 0
    var lon = 0
    override fun observeDataChange() {

    }

    @SuppressLint("SetTextI18n", "SimpleDateFormat")
    override fun initView() {
        mDataBinding.imageView4.setOnClickListener { finish() }
        lifecycleScope.launch {
            timer.schedule(object : TimerTask(){
                @SuppressLint("SimpleDateFormat")
                override fun run() {
                    runOnUiThread {
                        val time = SimpleDateFormat("HH:mm:ss").format(Date())
                        val parts = time.split(":")
                        val hour = parts[0].toInt()
                        val minute = parts[1].toInt()
                        mDataBinding.currentTime.text = time
                        if (hour>13){
                            mDataBinding.attendanceName.text = "下午打卡"
                            mDataBinding.attendanceTime.text = "13:30 - 18:00"
                        }else{
                            mDataBinding.attendanceName.text = "上午打卡"
                            mDataBinding.attendanceTime.text = "09:00 - 12:00"
                        }

                    }
                }
            },0,1000)
        }

        val now = SimpleDateFormat("yyyy年MM月dd日").format(Date())
        val dayOfWeek = SimpleDateFormat("EEEE", Locale.CHINA).format(Date())
        mDataBinding.currentDate.text = "$now $dayOfWeek"

        getLocal()

        val time = SimpleDateFormat("HH:mm:ss").format(Date())
        val parts = time.split(":")
        val hour = parts[0].toInt()
        val minute = parts[1].toInt()

        val clickListener = View.OnClickListener {
            // 使用前检查Activity是否存活
            if (!isDestroyed) {
                if (hour>13){
                    vm.addAttendance(
                        AttendanceEntity(
                            SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Date()),
                            "lat:${lat},lon:${lon}",
                            0,
                            mDataBinding.address.text.toString(),
                            SimpleDateFormat("yyyy/MM/dd 09:00:00").format(Date()),
                            "1",
                            438
                        )
                    )
                }else{
                    vm.addAttendance(AttendanceEntity(
                        SimpleDateFormat("yyyy/MM/dd 18:00:00").format(Date()),
                        "lat:${lat},lon:${lon}",
                        0,
                        mDataBinding.address.text.toString(),
                        SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Date()),
                        "1",
                        438
                    ))
                }
            }
        }

        mDataBinding.attendance.setOnClickListener(clickListener)

        vm.addAttendanceSuccess.observe(this){
            ToastUtils.showLong("打卡成功")
            finish()
        }

    }

    override fun getLayoutId(): Int = R.layout.activity_clock_in

    //声明AMapLocationClientOption对象
    var mLocationOption: AMapLocationClientOption? = null
    //声明AMapLocationClient类对象
    var mLocationClient: AMapLocationClient? = null

    //声明定位回调监听器
    private val mLocationListener = AMapLocationListener{amapLocation->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
     //可在其中解析amapLocation获取相应内容。
                Log.i("local", ": 地址：${amapLocation.latitude},${amapLocation.longitude}}")
                lat = amapLocation.latitude.toInt()
                lon = amapLocation.longitude.toInt()
                var geocoderSearch = GeocodeSearch(this);
                geocoderSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
                    override fun onRegeocodeSearched(p0: RegeocodeResult?, p1: Int) {
                        p0?.run {
                            val address = regeocodeAddress.formatAddress
                            Log.i("address", "onRegeocodeSearched: $address")
                            mDataBinding.address.text = address
                        }
                    }

                    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {

                    }

                })

                // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系

                // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                val query = RegeocodeQuery(LatLonPoint(amapLocation.latitude, amapLocation.longitude), 200f, GeocodeSearch.AMAP)

                geocoderSearch.getFromLocationAsyn(query)
            }else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError","location Error, ErrCode:"
                        + amapLocation.errorCode + ", errInfo:"
                        + amapLocation.errorInfo
                );
            }
        }
    }
    private fun getLocal() {

//初始化定位
        mLocationClient = AMapLocationClient(applicationContext)

//设置定位回调监听
        mLocationClient!!.setLocationListener(mLocationListener)

//初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()

        val option = AMapLocationClientOption()
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        option.locationPurpose = AMapLocationClientOption.AMapLocationPurpose.SignIn
        if (null != mLocationClient) {
            mLocationClient!!.setLocationOption(option)
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient!!.stopLocation()
            mLocationClient!!.startLocation()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        timer.cancel();  // 终止 Timer
        timer.purge();   // 清空任务队列
        if (mLocationClient != null) {
            mLocationClient!!.unRegisterLocationListener(mLocationListener); // 移除监听
            mLocationClient!!.stopLocation(); // 停止定位
            mLocationClient!!.onDestroy();    // 销毁定位客户端（部分 SDK 需要）
            mLocationClient = null;
        }
    }




}